import { Component, OnInit } from '@angular/core';
import { AxiosService } from '../../axios.service';
import { LocalStorageService } from 'src/app/myService/local-storage.service';
import { DatePipe } from '@angular/common';
import { Router } from '@angular/router';
import { Key } from 'protractor';

@Component({
  selector: 'app-process',
  templateUrl: './process.component.html',
  styleUrls: ['./process.component.scss'],
  providers: [DatePipe]
})
export class ProcessComponent implements OnInit {

  isVisible;
  isOkLoading;
  filterEsData;
  item;
  item2;
  add19code;//编辑19码
  isOkLoading19Code;
  coderq;//加工日期
  bbcc;//班次

  addCNCData;//添加工程师
  isOkLoadingCNC;

  fileInfom;//显示工单对应的文件信息
  isOkLoadingfileInfom;

  isFileVisible;
  isFileOkLoading;

  addAudit;//主管审核
  isOkLoadingAudit;
  public auditRemark = [];//审核备注
  public auditRemark2: string = "";//审核备注

  fileStatus;//主管审核状态
  fileStatus0;//未审核
  fileStatus1;//已审核
  fileStatus2;//被退回

  codeDate;//编程期限
  first: any;//首个19码
  tail: any;//结尾19码
  newCode19;//提示已存在的19码
  show19code;//是否显示提示信息
  selectName;//选中的工程师

  unionOrder;//工单号

  splitJudge: string = ',';

  //所有工单数据
  public tempData = [];
  //意同tempData
  public dataTemp = [];

  //工单对应的工件信息
  public workData = [];
  //意同workData
  public dataWork = [];
  public selCNCData = [];

  public workName;//下载时需补齐的文件路径
  public link;//下载链接
  estimate_time; //預計時間
  listfd = [];
  zplist;
  zpkey;

  public CNCData1 = [
    { 'title': '1號機 ', 'checked': false, 'select': 0 },
    { 'title': '2號機 ', 'checked': false, 'select': 1 },
    { 'title': '4號機 ', 'checked': false, 'select': 2 },
    { 'title': '5號機 ', 'checked': false, 'select': 3 },
    { 'title': '6號機 ', 'checked': false, 'select': 4 },
    { 'title': '7號機 ', 'checked': false, 'select': 5 },
    { 'title': '9號 走芯機', 'checked': false, 'select': 6 }
  ];
  //CNC机台数组
  public Radio = [];
  radioValue = '';
  public checked: Boolean = false;//指派CNC单选框
  public CNCData = [];
  public selCNCName;//
  public union_order;
  public sheet_order;
  // public engPerson = []; // 指派CNC


  // 接收要修改的数据
  updateData;

  public unionorder: any;//"WAKS20200304ZCH002",
  public newValue: any;//"新值"
  name;//"表中栏位名称",
  id;//文件信息id

  selectData = [];
  newArr = []; //定义空的新数组

  code19Data = [];//存放19码的数组

  public listOfData = [];//工单文件区数据

  fileName;//文件名
  filePath;//文件路径
  fileData;//得到的base64格式数据

  checkBoxStatus = [
    { 'title': '進行中', 'checked': true, 'select': 0 },
    { 'title': '已完成', 'checked': false, 'select': 1 }
  ];

  //1號機台 2號機台 3號機台 4號機台
  selectStatus = ["All",]

  infom = [
    { 'value': 'ok' },
    { 'value': '格式錯誤' },
    { 'value': '時間錯誤' },
    { 'value': '標註有問題' },
    { 'value': '信息錯誤' },
    { 'value': '信息有遺漏' },
    { 'value': '信息不完整' },
    { 'value': '請補充信息' }
  ];
  checkable;//备注信息
  selectedTags: string[] = [];

  constructor(
    public axios: AxiosService,
    private storage: LocalStorageService,
    private datePipe: DatePipe,
    private router: Router
  ) { }

  ngOnInit(): void {
    //获取全部数据
    // debugger
    this.getAllData();
    //获取当前时间
    var date = new Date();
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    var day2;
    var month2;
    if (month < 10) {
      month2 = "0" + month;
    } else {
      month2 = month;
    }
    if (day < 10) {
      day2 = "0" + day;
    } else {
      day2 = day;
    }
    var nowDate = year + "-" + month2 + "-" + day2;
    console.log(nowDate)
    this.axios.axiosPost("QueryCncInfo", { "status": "cncTime", "starttime": nowDate }).then((data) => {
      console.log(data)
      for (var i = 0; i < data["order"].length; i++) {
        this.selectStatus.push(data["order"][i].name + " ( " + data["order"][i].cncTime + " )")
      }
    })
    // this.addCNCData()
  }

  //查询所有工单信息
  getAllData() {
    this.selectData = [];
    this.axios.axiosPost('QueryUnionOrder', { "stage": 2, "stageValue": 1, "status": 10 })
      .then((data) => {
        this.listfd = [];
        if (data) {
          this.tempData = data['order'];
          this.dataTemp = this.tempData;
          console.log(this.dataTemp)
          const addData = this.dataTemp.filter(res => res['status'] === 0);
          this.selectData = this.selectData.concat(addData);
          for (var i = 0; i < this.selectData.length; i++) {
            this.listfd.push(new Array);
          }
        }
      })
      .catch((err) => {
        console.log(err);
      })
  }

  //查询工单对应的工件信息
  QueryWorkOrder(key) {
    console.log(key)
    this.axios.axiosPost('QueryWorkOrder', { 'unionorder': this.selectData[key].union_order, "status": 2, "type": 1 })
      .then((data) => {
        console.log(data)
        if (data['result'] === 'ok') {
          this.listfd[key] = new Array;
          this.workData[key] = data['order'];
          this.dataWork = data['order'];
          // this.storage.setStorageData('result', this.workData);
          console.log(this.workData.length)
          for (var i = 0; i < this.workData.length; i++) {
            this.listfd[key].push(new Array)
          }
        }
      })
      .catch((err) => {
        console.log(err);
      })
  }

  //查询工单状态
  doingForm(data) {
    // 选中
    if (!data.checked) {
      const addData = this.dataTemp.filter(res => res['status'] === data.select);
      this.selectData = this.selectData.concat(addData);
      console.log(this.selectData)
    }
    // 未选中
    if (data.checked) {
      const deleteData = this.selectData.filter(res => res['status'] === data.select);
      this.selectData = this.selectData.filter(item => !deleteData.some(ele => ele['status'] === item['status']));
      console.log(this.selectData)
    }
  }

  //CNC机台选择
  selStatus(item) {
    item.checked = !item.checked;
    this.selCNC(item);
  }

  //筛选CNC机台
  selCNC(data) {
    // debugger
    console.log(data)
    // 选中
    if (data.checked) {
      const addCNC = this.dataWork.filter(res => res['cnc_name'] === data.select);
      console.log(addCNC)
      this.selCNCData = this.selCNCData.concat(addCNC);
      console.log(this.selCNCData)
    }
    // 未选中
    if (!data.checked) {
      const deleteCNC = this.workData.filter(res => res['cnc_name'] === data.select);
      console.log(deleteCNC)
      this.selCNCData = this.workData.filter(item => !deleteCNC.some(ele => ele['cnc_name'] === item['cnc_name']));
      console.log(this.selCNCData)
    }
    // this.workData = [];
    this.workData = this.selCNCData;
  }


  //取消工單
  handleCancel() {
    this.isVisible = false;
    this.auditRemark2 = "";
  }
  //确定取消按钮
  handleOk() {
    // debugger
    if (this.auditRemark2) {
      this.isOkLoading = true;
      this.isVisible = false;
      this.isOkLoading = false;
      this.axios.axiosPost('UpdateUnionOrder2', { 'unionorder': this.updateData.union_order, 'name1': 'status', 'newValue1': '2', 'name2': 'cancel_remark', 'newValue2': this.auditRemark2, })
        .then((data) => {
          console.log(data)
          // debugger
          if (data['result'] === 'ok') {
            // this.getDoingData();
            this.getAllData();
          }
        })
    } else {
      alert("未填寫刪除工單的原因")
    }
  }
  showModal(item) {
    this.isVisible = true;
    this.updateData = item;
  }

  //点击添加19码
  addCode19(item) {
    console.log(item)

    this.first = item.code19.split(',')[0];
    this.tail = item.code19.split(',')[1];
    this.add19code = true;
    this.show19code = false;
    this.updateData = item;
  }
  //确定添加19码
  add19CodeOk() {
    this.isOkLoading19Code = true;
    this.add19code = false;
    this.isOkLoading19Code = false;
    console.log(this.first);
    if (this.first === '' && this.tail === '') {
      alert("输入框不能都为空！")
    }
    let A = this.first.substr(0, 15);//first前15位
    let a = parseInt(this.first.substr(15, 4));//first后4位
    let B;
    let b;
    if (this.tail === '') {
      B = '';
      b = 0;
    } else {
      B = this.tail.substr(0, 15);
      b = parseInt(this.tail.substr(15, 4));
    }
    console.log(a, b)
    // 判断前15位是否一致
    if (A === B) {
      //首位19码必须小于末尾19码
      if (a < b) {
        this.axios.axiosPost('UpdateUnionOrder', { 'unionorder': this.updateData.union_order, 'name': 'code19', 'newValue': this.first + ',' + this.tail })
          .then((data) => {
            console.log(data)
            if (data['result'] === 'ok') {
              this.getAllData();
              this.add19code = false;
              this.show19code = false;
            } else if (data['result'] === 'error') {
              this.show19code = true;
              this.newCode19 = data['code19'];
              this.add19code = true;
            }
          })
      } else {
        this.add19code = true;
        alert("末尾19码不能小于首位19码")
      }
    } else {
      this.add19code = true;
      alert("输入的首尾19码前15位不一致")
    }
  }
  //取消添加19码
  CancelAdd19Code() {
    this.add19code = false;
  }

  //点击显示CNC列表
  addCNC(item,a,b) {
    this.Radio = [];
    this.union_order = item.union_order;
    this.sheet_order = item.sheet_order;
    this.codeDate = item.end_date;
    this.estimate_time = item.estimate_time;
    this.bbcc = item.banci;
    this.coderq = item.jiagongriqi;
    this.zplist=item;
    this.zpkey=b;
    this.selCNCName=a;
    if (item.cnc_name.trim() !== '') {
      this.radioValue = item.cnc_name.trim();
      console.log("+++" + this.radioValue + "+++")
    } else {
      this.radioValue = '';
    }
    this.addCNCData = true;
    this.axios.axiosPost('QueryCncInfo')
      .then((data) => {
        console.log(data)
        if (data['result'] === 'ok') {
          this.CNCData = data['order'];
          for (let i = 0; i < this.CNCData.length; i++) {
            // debugger
            this.Radio.push({ label: this.CNCData[i].name.trim(), value: this.CNCData[i].name.trim() });
          }
          console.log(this.Radio)
        }
      })
  }

  selectCNC(value) {
    this.radioValue = value;
    console.log("======" + this.radioValue + "======")
  }

  //取消指派CNC
  CancelAddCNC() {
    this.addCNCData = false;
  }

  //确定指派CNC
  AddCNCOK() {
    console.log(this.coderq, this.bbcc)
    this.coderq = this.datePipe.transform(this.coderq, 'yyyy-MM-dd');
    console.log(this.coderq)
    this.codeDate = this.datePipe.transform(this.codeDate, 'yyyy-MM-dd');
    if (this.codeDate == null || this.codeDate == "") {
      alert("未填寫加工期限")
    } else if (this.estimate_time == null || this.estimate_time == "") {
      alert("未填寫預計時間")
    } else {
      this.axios.axiosPost('UpdateWorkOrder', {
        'unionorder': this.union_order, 'workorder': this.sheet_order,id:this.zplist.id,
        'cnc': this.radioValue,
        'end_date': this.codeDate, 'estimate_time': this.estimate_time, "banci": this.bbcc, "jiagongriqi": this.coderq
      })
        .then((data) => {
          this.CancelAddCNC();
          console.log(data)
          if (data['result'] === 'ok') {
            if(this.zplist.chaidan!=1){
              this.QueryWorkOrder(this.selCNCName);
            }else{
              this.QueryWorkOrder2(this.zplist,this.selCNCName,this.zpkey)
            }
          }
        })
    }
    console.log(this.codeDate);

  }


  //定义函数：判断元素是否在数组中
  unique(arr: any) {
    var array = [];
    for (var i = 0; i < arr.length; i++) {
      if (array.indexOf(arr[i]) === -1) {
        array.push(arr[i])
      }
    }
    return array;
  }

  currentPageDataChange(qqq) {

  }

  //点击图标显示此工单的文件信息
  downLoad(infom) {
    // debugger
    this.fileInfom = true;
    console.log(infom)
    this.updateData = infom;
    this.axios.axiosPost('QueryWorkFiles', { 'unionorder': this.updateData.union_order, 'workorder': this.updateData.name })
      .then((data) => {
        console.log(data)
        if (data['result'] === 'ok') {
          this.listOfData = data['files'];
          this.workName = this.updateData.union_order;
          console.log(this.listOfData)
        }
      })
  }

  CancelShow() {
    this.fileInfom = false;
  }

  ShowOK() {
    this.isOkLoadingfileInfom = true;
    this.fileInfom = false;
    this.isOkLoadingfileInfom = false;
  }

  //主管审核
  ClickAudit(data, key) {
    console.log('=============== \n', data, key);
    this.addAudit = true;
    this.fileStatus = data.file_status;
    this.id = data.id;
    this.filePath = data.file_path;
  }

  //取消审核
  CancelAudit() {
    this.addAudit = false;
  }

  //确定审核按钮
  auditOk() {
    this.isOkLoadingAudit = true;
    this.addAudit = false;
    this.isOkLoadingAudit = false;
    // debugger
    let index = this.auditRemark.indexOf('ok');//判断是否含有此值
    if (index === 0) {
      this.fileStatus = 1;//审核通过
    } else {
      this.fileStatus = 2;//已退回
    }
    console.log(this.id)
    this.axios.axiosPost('UpdateWorkFile', {
      'id': this.id,
      'name': 'file_status', 'newValue': this.fileStatus,
      'name2': 'remark', 'newValue2': this.auditRemark
    })
      .then((data) => {
        console.log(data)
        if (data['result'] === 'ok') {
          debugger
          this.axios.axiosPost('ParseBOMFile', { 'filepath': this.filePath, 'action': 'check' })
            .then((data) => {
              console.log(data)
              if (data['result'] === 'ok') {
                console.log(this.listOfData)
                this.downLoad(this.listOfData);
              }
            })
        }
      })
  }
  //填写审核备注
  handleChange(checked: boolean, tag: string): void {
    this.selectedTags = [];
    if (checked) {
      this.selectedTags.push(tag);
    } else {
      this.selectedTags = this.selectedTags.filter(t => t !== tag);
    }
    console.log(this.selectedTags);
    this.auditRemark = this.selectedTags[0]['value'];//赋值
  }

  //下载文件
  downLoadFile(data) {
    console.log(data)
    this.fileName = data.file_name;
    this.link = this.axios.domainTest1 + this.workName + '/' + this.fileName;
  }

  handleFileCancel() {
    this.isFileVisible = false;
  }

  //删除文件信息
  showDelFile(data) {
    this.isFileVisible = true;
    console.log(data)
    this.id = data.id;
  }

  delFileOk() {
    this.isFileOkLoading = true;
    this.isFileVisible = false;
    this.isFileOkLoading = false;
    this.axios.axiosPost('DeleteWorkFile', { 'id': this.id })
      .then((data) => {
        console.log(data)
        if (data['result'] === 'ok') {
          let listData = this.listOfData.filter(res => res['id'] !== this.id)
          this.listOfData = listData;
        }
      })
  }

  //点击工单号显示CNC
  showCNC(item) {
    console.log(item)
    const data = {};
    data['union_order'] = item.union_order;
    console.log(data['union_order'])
    data['from'] = "jg";
    this.router.navigate(['/CNC', data])
    // {queryParams: {refersh: new Date().getTime()}}
  }

  btn_CNC(data) {
    console.log(data)
    const CNCnum = {};
    if (data == "All") {
      CNCnum['select'] = "";

    } else {
      CNCnum['select'] = data.substring(0, data.indexOf("(") - 1);

    }
    CNCnum['from'] = "jg";
    console.log(CNCnum['select'])
    this.router.navigate(['/CNC', CNCnum]);
  }
  QueryWorkOrder2(a, b, c) {
    console.log("触发", a)
    this.axios.axiosPost("QueryCncDataSubOrder", { "unionorder": a.unionorder, "workorder": a.sheet_order }).then((data) => {
      console.log(data);
      if (data["result"] == "ok") {
        this.listfd[b][c] = data["order"];
      }
    })
  }
}
